package ldkxingzhe.l365calendar.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;

import java.lang.reflect.Method;

import ldkxingzhe.l365calendar.R;
import ldkxingzhe.l365calendar.fragment.AllEditFragmentBase;
import ldkxingzhe.l365calendar.fragment.NoteEditFragment;
import ldkxingzhe.l365calendar.fragment.ScheduleAlarmFragment;
import ldkxingzhe.l365calendar.fragment.ScheduleAlertSetupFragment;
import ldkxingzhe.l365calendar.fragment.ScheduleCategoryFragment;
import ldkxingzhe.l365calendar.fragment.ScheduleDescriptionFragment;
import ldkxingzhe.l365calendar.fragment.ScheduleFragment;

/**
 *
 * Created by ke on 16-1-24.
 */
public class AllEditActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
    @SuppressWarnings("unused")
    private final static String TAG = "AllEditFragmentBase";

    public static final String TYPE = "type";
    public static final String CLASS_INDEX = "class_index";
    public static final String TITLE_NAME = "title_name";
    public static final int TWO_TABS = 0;
    public static final int SINGLE_TAB = 1;

    private ViewPager viewPager;
    private RadioButton[] radioButtons = new RadioButton[2];
    private View[] indicators = new View[2];

    private final static Class<?>[] fragmentClass = {ScheduleFragment.class, NoteEditFragment.class};
    private final static Class<?>[] singleFragmentClass = {
            ScheduleCategoryFragment.class, ScheduleDescriptionFragment.class,       // 0,1
            ScheduleAlarmFragment.class, ScheduleAlertSetupFragment.class      // 2,3
    };
    private AllEditFragmentBase[] fragments = new AllEditFragmentBase[fragmentClass.length];

    private int type;

    private PagerAdapter pageAdapter;
    private View saveBtn;
    private AllEditFragmentBase singleFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_edit);
        type = getIntent().getIntExtra(TYPE, TWO_TABS);
        initTitle(findViewById(R.id.title_layout));
        viewPager = findView(R.id.view_pager_with_scroll);
        pageAdapter = new AllEditFragmentAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pageAdapter);
        viewPager.setOnPageChangeListener(this);
    }

    private void initTitle(View titleLayout) {
        if(type == TWO_TABS){
            initTwoTabs(titleLayout);
        }else{
            initSingleTab(titleLayout);
        }

        View cancelBtn = findViewById(R.id.title_left_text);
        saveBtn = findView(R.id.title_right_text);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCurrentFragment().onSaveClick();
            }
        });
    }

    private void initSingleTab(View titleLayout) {
        titleLayout.findViewById(R.id.tabs).setVisibility(View.GONE);
        TextView titleText = (TextView) titleLayout.findViewById(R.id.title);
        titleText.setVisibility(View.VISIBLE);
        int fragmentIndex = getIntent().getIntExtra(CLASS_INDEX, 0);
        String title;
        if(getIntent().hasExtra(TITLE_NAME)){
            title = getIntent().getStringExtra(TITLE_NAME);
        }else{
            title = "NO NAME";
        }
        titleText.setText(title);
        Class<?> clazz = singleFragmentClass[fragmentIndex];
        try {
            Method newInstance = clazz.getDeclaredMethod("newInstance", Bundle.class);
            singleFragment = (AllEditFragmentBase) newInstance.invoke(clazz, getIntent().getExtras());
        } catch (Exception e) {
            try {
                singleFragment = (AllEditFragmentBase) clazz.newInstance();
            } catch (Exception e1) {
                throw new RuntimeException(e1.getMessage(), e1);
            }
        }
    }

    private void initTwoTabs(View titleLayout) {
        radioButtons[0] = (RadioButton) titleLayout.findViewById(R.id.title_schedule);
        radioButtons[1] = (RadioButton) titleLayout.findViewById(R.id.title_todo);

        indicators[0] = titleLayout.findViewById(R.id.iv_tab_schedule);
        indicators[1] = titleLayout.findViewById(R.id.iv_tab_todo);

        for(int i = 0; i < radioButtons.length; i++){
            final int j = i;
            radioButtons[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        indicators[j].setVisibility(View.VISIBLE);
                        viewPager.setCurrentItem(j);
                    }else{
                        indicators[j].setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    /**
     * 设置保存按钮的状态　
     */
    public void setSaveEnable(boolean enable){
        saveBtn.setEnabled(enable);
    }

    @Override
    public void onBackPressed() {
        if(getCurrentFragment().onCancelClick()) return;
        super.onBackPressed();
    }

    private AllEditFragmentBase getCurrentFragment(){
        if(type == TWO_TABS){
            return fragments[viewPager.getCurrentItem()];
        }
        return singleFragment;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if(type == TWO_TABS){
            radioButtons[position].setChecked(true);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class AllEditFragmentAdapter extends FragmentPagerAdapter{

        public AllEditFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if(type == TWO_TABS){
                AllEditFragmentBase result = null;
                try {
                    result = (AllEditFragmentBase) fragmentClass[position].newInstance();
                } catch (Exception e) {
                    Log.v(TAG, e.getMessage(), e);
                }
                fragments[position] = result;
                return result;
            }else{
                return singleFragment;
            }
        }

        @Override
        public int getCount() {
            if(type == TWO_TABS){
                return fragmentClass.length;
            }
            return 1;
        }
    }
}
